﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using RadinfMagazynier3.Tools;
using RadinfMagazynier3.DataSets;
using RadinfMagazynier;

namespace RadinfMagazynier3.Forms
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        public static MagazynierDS DataSource = new MagazynierDS();
        public static List<string> Logs = new List<string>();

        #region CTOR
        public MainForm()
        {
            InitializeComponent();
            loadData();
            setDataBinding();
        }

        private void setDataBinding()
        {
            setDataBinding(string.Empty);
        }

        private void setDataBinding(string filter)
        {
            DataView dv = new DataView(DataSource.ITEM, filter, "CODE ASC", DataViewRowState.CurrentRows);
            this.gridControl1.DataSource = dv;
        }
        #endregion

        #region LOAD / SAVE
        private void loadData()
        {
            string dataFilePath = Globals.XML_FILES.RADINF_MAGAZYNIER_DATA;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (!File.Exists(dataFilePath))
                    createDataFile(Globals.XML_FILES.RADINF_MAG_DATA_DIR, dataFilePath);

                DataSource.ReadXml(dataFilePath);
                validateLoadedBackUp(dataFilePath);

                Cursor.Current = Cursors.Default;
            }
            catch (Exception exc)
            {
                RadinfTools.ShowError("MainForm.loadData()", exc.Message);
            }
        }

        private void validateLoadedBackUp(string path)
        {
            List<string> doubledCodes = getDoubledRecords();
            if (doubledCodes.Count > 0)
            {
                string codes = "Zdublowane kody: ";
                foreach (string code in doubledCodes)
                {
                    codes += code + " | ";
                }
                RadinfTools.ShowError("MainForm.readBackUpToolStripMenuItem_Click()", codes);
            }

            DataSet tempDS = new DataSet();
            tempDS.ReadXml(path, XmlReadMode.InferSchema);
            if (tempDS.Tables.Contains("ITEM"))
            {
                int magazynierCounter = DataSource.ITEM.Rows.Count;
                int tempCounter = tempDS.Tables["ITEM"].Rows.Count;
                if (magazynierCounter != tempCounter)
                {
                    RadinfTools.ShowError("MainForm.readBackUpToolStripMenuItem_Click()", "Ilość pozycji wczytanych nie jest rowna ilości pozycji zapisanych, sprawdz plik kopii bezpieczeństwa: " + path);
                }
            }
        }

        private List<string> getDoubledRecords()
        {
            List<string> codes = new List<string>();
            List<string> doubledCodes = new List<string>();
            string currCode = string.Empty;

            foreach (DataRow row in DataSource.ITEM.Rows)
            {
                currCode = RadinfTools.ConvertToString(row["CODE"]);
                if (!codes.Contains(currCode))
                    codes.Add(currCode);
                else if (!doubledCodes.Contains(currCode))
                    doubledCodes.Add(currCode);
            }

            return doubledCodes;
        }

        private void saveData()
        {
            DataSource.AcceptChanges();

            string dataFilePath = Globals.XML_FILES.RADINF_MAGAZYNIER_DATA;
            try
            {
                if (!File.Exists(dataFilePath))
                    createDataFile(Globals.XML_FILES.RADINF_MAG_DATA_DIR, dataFilePath);

                DataSource.WriteXml(dataFilePath);
            }
            catch (Exception exc)
            {
                RadinfTools.ShowError("MainForm.saveData()", exc.Message);
            }
        }

        private void createDataFile(string directory, string fileName)
        {
            FileInfo fi = new FileInfo(fileName);
            if (Directory.Exists(directory))
            {
                fi.Create();
            }
            else
            {
                Directory.CreateDirectory(directory);
                fi.Create();
            }
        }

        private void writeBackUps()
        {
            bool firstWrite = false;
            try
            {
                string dataDir = "Directory with data: " + Globals.XML_FILES.RADINF_MAG_DATA_DIR;
                string appDir = "Applications directory: " + Application.StartupPath;

                string backUpsMainDir = "C:\\RRMagazynier_LOGS\\";
                string backUpFileName = DateTime.Now.ToString() + "_logs.xml";
                backUpFileName = backUpFileName.Replace("/", "_");
                backUpFileName = backUpFileName.Replace(" ", "_");
                backUpFileName = backUpFileName.Replace(":", "_");

                if (!Directory.Exists(backUpsMainDir))
                {
                    Directory.CreateDirectory(backUpsMainDir);
                }

                DataSource.WriteXml(backUpsMainDir + backUpFileName);

                StreamWriter streamWriter = null;

                if (File.Exists(backUpsMainDir + "logs.txt"))
                {
                    streamWriter = new StreamWriter(backUpsMainDir + "logs.txt", true);
                }
                else
                {
                    FileStream fileStream = new FileStream(backUpsMainDir + "logs.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    streamWriter = new StreamWriter(fileStream);
                    firstWrite = true;
                }

                if (firstWrite)
                {
                    streamWriter.WriteLine(dataDir);
                    streamWriter.WriteLine(appDir);
                }
                streamWriter.WriteLine("----------------------------------------------------");
                streamWriter.WriteLine("Last modify: " + DateTime.Now.ToString());
                foreach (string err in Logs)
                {
                    streamWriter.WriteLine(err);
                }
                streamWriter.WriteLine("____________________________________________________");
                streamWriter.Close();
            }
            catch (Exception exc)
            {
                RadinfTools.ShowError("MainForm.writeBackUps()", exc.Message);
            }
        }
        #endregion

        #region TOOLS
        private void addNewItem()
        {
            ItemForm frm = new ItemForm(null);
            frm.ShowDialog();
        }

        private void editItem()
        {
            MagazynierDS.ITEMRow itemDR = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle) as MagazynierDS.ITEMRow;
            if (itemDR != null && itemDR.RowState != DataRowState.Deleted)
            {
                ItemForm frm = new ItemForm(itemDR);
                frm.ShowDialog();
            }
        }

        private void deleteItem()
        {
            DataRow itemDR = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            if (itemDR != null && itemDR.RowState != DataRowState.Deleted)
            {
                itemDR.Delete();
            }
        }

        private void setGridFilter(string filter)
        {
            ((DataView)this.gridView1.DataSource).RowFilter = filter;
        }

        private void importOldData()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.DefaultExt = "xml";
            ofd.Filter = "pliki XML (*.xml)|*.xml";
            ofd.Title = "Podaj plik ze starą bazą danych";
            ofd.InitialDirectory = "C:";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    OldMagazynierDS oldDS = new OldMagazynierDS();
                    oldDS.ReadXml(ofd.FileName);
                    oldDS.AcceptChanges();
                    ImportTools.ImportDataFromOldSchema(oldDS);
                    MainForm.DataSource.AcceptChanges();
                    Cursor.Current = Cursors.Default;
                }
                catch (Exception exc)
                {
                    RadinfTools.ShowError("MainForm.importOldData()", exc.Message);
                }
            }
        }
        #endregion

        #region EVENTS
        #region MENU ITEMS EVENTS
        #region PLIK
        private void ustawieniaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsForm frm = new SettingsForm(DataSource);
            frm.ShowDialog();
        }

        private void stworzKopieToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.DefaultExt = "xml";
            sfd.Filter = "pliki XML (*.xml)|*.xml";
            sfd.AddExtension = true;
            sfd.Title = "Wybierz lokalizację dla kopii bezpiecześnstwa";
            sfd.InitialDirectory = "C:";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string fileName = sfd.FileName;
                string fileDir = fileName.Substring(0, fileName.LastIndexOf('\\'));
                try
                {
                    DataSource.WriteXml(fileName);
                }
                catch (Exception exc)
                {
                    RadinfTools.ShowError("MainForm.stwórzKopięToolStripMenuItem_Click()", exc.Message);
                }
            }
        }

        private void wczytajKopieToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.DefaultExt = "xml";
            ofd.Filter = "pliki XML (*.xml)|*.xml";
            ofd.Title = "Podaj plik z kopią bezpieczeństwa";
            ofd.InitialDirectory = "C:";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    DataSource.Clear();
                    Cursor.Current = Cursors.WaitCursor;
                    DataSource.ReadXml(ofd.FileName);

                    validateLoadedBackUp(ofd.FileName);

                    Cursor.Current = Cursors.Default;
                }
                catch (Exception exc)
                {
                    RadinfTools.ShowError("MainForm.readBackUpToolStripMenuItem_Click()", exc.Message);
                }
            }
        }

        private void zakonczToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion
        #region MAGAZYN
        private void nowaPozycjaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addNewItem();
        }

        private void remanentMenuItem_Click(object sender, EventArgs e)
        {
            StockTacking stockTacking = new StockTacking();
            stockTacking.DataSource = MainForm.DataSource;
            try
            {
                stockTacking.ExportToPdf("c:\\remanent.pdf");
                stockTacking.ShowPreviewDialog();
                MainForm.DataSource.STORETACKING.Clear();
                MainForm.DataSource.HEADER.Clear();
            }
            catch (Exception exc)
            {
                RadinfTools.ShowError("MainForm.showStoreMenuItem_Click()", exc.Message);
            }
        }

        private void sprawdzZdublowaneRekordyToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
        #endregion
        #region POMOC
        private void oProgramieToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm frm = new AboutForm();
            frm.ShowDialog();
        }

        private void pomocToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            HelpForm frm = new HelpForm();
            frm.ShowDialog();
        }
        #endregion
        #endregion

        private void btnDelete_Click(object sender, EventArgs e)
        {
            deleteItem();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            editItem();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void teCode_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            teName.EditValue = null;

            string searchCriteria = RadinfTools.ConvertToString(e.NewValue);
            if (!String.IsNullOrEmpty(searchCriteria))
            {
                searchCriteria = "CODE LIKE '" + searchCriteria + "%'";
                setGridFilter(searchCriteria);
            }
            else
                setGridFilter(string.Empty);
        }

        private void teName_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            teCode.EditValue = null;

            string searchCriteria = RadinfTools.ConvertToString(e.NewValue);
            if (!String.IsNullOrEmpty(searchCriteria))
            {
                searchCriteria = "NAME LIKE '" + searchCriteria + "%'";
                setGridFilter(searchCriteria);
            }
            else
                setGridFilter(string.Empty);
        }

        private void repPrice_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            string decimalSeparator = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
            string oldValue = e.DisplayText;
            if (oldValue.Contains(decimalSeparator))
            {
                if (oldValue.LastIndexOf(decimalSeparator) == (oldValue.Length - 2))
                    e.DisplayText = oldValue + "0";
            }
            else
                e.DisplayText = oldValue + decimalSeparator + "00";
        }

        private void repVat_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            long vatID = RadinfTools.ConvertToLong(e.DisplayText);
            if (vatID > -1)
            {
                DataRow[] vatRow = MainForm.DataSource.VAT.Select("ID = " + vatID.ToString());
                if (vatRow.Length == 1)
                {
                    e.DisplayText = RadinfTools.ConvertToString(vatRow[0]["DESC"]);
                }
            }
        }

        private void repMeasure_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            long measureID = RadinfTools.ConvertToLong(e.DisplayText);
            if (measureID > -1)
            {
                e.DisplayText = ItemTools.GetMeasureDescription(measureID);
            }
        }

        private void MainForm_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            writeBackUps();
            saveData();
            Cursor.Current = Cursors.Default;
        }

        private void MainForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Insert)
                addNewItem();
            else if (e.KeyCode == Keys.Enter)
                editItem();
            else if (e.KeyCode == Keys.Delete)
                deleteItem();
            else if (e.Alt && e.Shift && e.KeyCode == Keys.I)
                importOldData();
        }
        #endregion        
    }
}